/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Form, Row, Col, DatePicker, Select, Input, TextArea, Button } from 'antd';
import moment from 'moment/moment';
import { debounce } from 'lodash';
import { connect } from 'dva';
import styles from '../../../commen.less';
import { crypto } from '@/utils/encryption';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

@connect(({ loading, setter, payment }) => ({
  setter,
  payment,
  getList: loading.effects['payment/getCollectionPaymentList'],
}))
@Form.create()
export default class SearchBar extends Component {
  componentWillUpdate(nextProps) {
    /**
     * 接收从回款清单带过来record的数据，设置给form表单进行明细查询
     *  */
    let isEqual = nextProps.checkDetail && nextProps.checkDetail == this.props.checkDetail;
    const {
      dispatch,
      payment: { searchFormValue },
      form,
    } = nextProps;

    if (nextProps.checkDetail && !isEqual) {
      const {
        record: { customer_name, big_customer_name, type, group_waybill_no },
        time: { endTime, startTime },
      } = nextProps.checkDetail;

      let value = {
        ...searchFormValue,
        data_start: startTime,
        data_end: endTime,
        customerSearch: customer_name || big_customer_name,
        collectionStatus: type,
        expressNumber: group_waybill_no,
      };

      // dispatch({  //将表单数据存入状态管理，方便代收货款页面调用
      //   type:"payment/save",
      //   payload:{
      //     searchFormValue: value
      //   }
      // })

      form.setFieldsValue({
        data_start: startTime,
        data_end: endTime,
        customerSearch: customer_name || big_customer_name,
        collectionStatus: type,
        expressNumber: group_waybill_no,
      });

      setTimeout(() => {
        this.handleSearch();
      }, 0);
    }
  }

  disabledDate = current => {
    return (
      current &&
      current >
        moment()
          .endOf('day')
          .subtract(0, 'days')
    );
  };

  getStationList = visible => {
    const { dispatch } = this.props;
    if (visible) {
      dispatch({
        type: 'setter/getYzList',
      });
    }
  };

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e, labe) => {
    this.setState({
      siteId: labe.props.value,
    });
  };

  changeSelect = value => {
    if (!value) {
      this.setState({
        siteId: 'all',
      });
    }
  };

  addDownLoad = debounce(
    type => {
      this.getFormValues(values => {
        delete values.collectionStatus;
        if (values.signStatus === undefined) {
          values.signStatus = '';
        }
        let payload = {
          ...values,
          collectionStatus: type,
        };

        const href = `/Api/orderManage/CollectionOfPayment/exportOrder?${this.serializeGetData(
          payload,
        )}`;

        crypto({
          url: href,
          options: {
            nonceKey: this.props.nonceKey,
            data: payload,
          },
        }).then(url => {
          let downloadElement = document.createElement('a');
          downloadElement.href = url;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  serializeGetData = params => {
    let paramsArray = [];
    Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]));
    let data = paramsArray.join('&');
    return data;
  };

  handleSearch = debounce(
    () => {
      // e.preventDefault();
      const { dispatch, source } = this.props;
      this.getFormValues(values => {
        let value = { ...values };
        if (source == 'payBack') {
          value.data_start = '';
          value.data_end = '';
        }

        dispatch({
          type: 'payment/getCollectionPaymentList',
          payload: {
            ...value,
          },
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  getFormValues = then => {
    const { form, dispatch } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.data_start = start;
        values.data_end = end;
        delete values.date;
      }
      dispatch({
        type: 'payment/save',
        payload: {
          searchFormValue: values,
        },
      });
      then(values);
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      setter,
      getList,
      payment: { searchFormValue },
    } = this.props;
    const {
      data_start,
      data_end,
      siteId,
      collectionStatus,
      customerSearch,
      expressNumber,
      signStatus,
      salesmanSearch,
      pickupCode,
      addresseeSearch,
    } = searchFormValue;

    const yzList = (setter && setter.yzList) || [];
    return (
      <Form layout="inline" style={{ marginBottom: 24 }} className={styles.search_form}>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator('date', {
                    initialValue: [moment(data_start), moment(data_end)],
                  })(
                    <RangePicker
                      style={{ width: '100%' }}
                      disabledDate={this.disabledDate}
                      placeholder={['开始日期', '结束日期']}
                    />,
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={20}>
                <Row type="flex" justify="space-between" gutter={[8]}>
                  <Col span={12}>
                    <FormItem>
                      {getFieldDecorator(`signStatus`, {
                        initialValue: signStatus,
                      })(
                        <Select width="100%" placeholder="是否已签收" allowClear>
                          <Option key="1" value="1">
                            未签收
                          </Option>
                          <Option key="2" value="2">
                            已签收
                          </Option>
                        </Select>,
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem>
                      {getFieldDecorator(`collectionStatus`, {
                        initialValue: collectionStatus,
                      })(
                        <Select width="100%" placeholder="是否已回款" allowClear>
                          <Option key="1" value="1">
                            未回款
                          </Option>
                          <Option key="2" value="2">
                            已回款
                          </Option>
                        </Select>,
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator(`salesmanSearch`, {
                    initialValue: salesmanSearch,
                  })(<Input allowClear width="100%" placeholder="请输入业务员手机或者姓名搜索" />)}
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col span={8}>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator('siteId', {
                    initialValue: siteId,
                  })(
                    <Select
                      onDropdownVisibleChange={this.getStationList}
                      filterOption={this.onFilterOperator}
                      placeholder="选择站点"
                      showSearch
                      allowClear
                      style={{ width: '100%' }}
                      onSelect={this.selectCurrency}
                      onChange={this.changeSelect}
                    >
                      <Option key="all" value="all">
                        全部站点
                      </Option>
                      {yzList.map(({ site_id, site_name }) => (
                        <Option key={`${site_id}`} value={site_id}>
                          {site_name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator(`customerSearch`, {
                    initialValue: customerSearch,
                  })(<Input allowClear width="100%" placeholder="请输入客户手机或者姓名搜索" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator(`addresseeSearch`, {
                    initialValue: addresseeSearch,
                  })(<Input allowClear width="100%" placeholder="请输入发件人手机或者姓名搜索" />)}
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col span={8}>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator(`expressNumber`, {
                    initialValue: expressNumber,
                  })(<Input width="100%" allowClear placeholder="输入运单号搜索" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={20}>
                <FormItem>
                  {getFieldDecorator(`pickupCode`, {
                    initialValue: pickupCode,
                  })(
                    <Input.TextArea
                      allowClear
                      autoSize={{ minRows: 3, maxRows: 5 }}
                      width="100%"
                      placeholder="请输入揽件码，多个揽件码用逗号分开"
                    />,
                  )}
                </FormItem>
              </Col>
            </Row>
          </Col>
        </Row>
        <Row type="flex" gutter={[8]}>
          <Col>
            <Button
              type="primary"
              icon="search"
              onClick={this.addDownLoad.bind(this, 2)}
              // loading={downloading}
            >
              下载当前已回款excel表格
            </Button>
          </Col>
          <Col>
            <Button
              type="primary"
              icon="search"
              onClick={this.addDownLoad.bind(this, 1)}
              // loading={downloading}
            >
              下载当前待回款excel表格
            </Button>
          </Col>
          <Col>
            <Button type="primary" icon="search" onClick={this.handleSearch} loading={getList}>
              查询
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }
}
